﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using QxFramework.Utilities;
using UnityEngine;
using UnityEngine.UI;

public class Maker : MonoBehaviour
{
    private List<KeyValuePair<string, GameObject>> _players = new List<KeyValuePair<string, GameObject>>();
    private List<string> _playerTeams = new List<string>();

    private Dictionary<string, List<Type>> _author = new Dictionary<string, List<Type>>();
    private Dictionary<Type, PlayerData> _datas = new Dictionary<Type, PlayerData>();

    private Transform _group;

    private Transform _authorList;
    private Transform _tankList;

    private Dropdown _teamSeletor;

    // Use this for initialization
    private void Start()
    {
        _group = new GameObject().transform;
        _group.name = "Players";
        _authorList = transform.Find("AuthorList/Scroll View/Viewport/Content");
        _tankList = transform.Find("TankList/Scroll View/Viewport/Content");
        _teamSeletor = GetComponentInChildren<Dropdown>();
        CollectClasses();
        CreateAuthorList();
    }

    private void CollectClasses()
    {
        string[] classes = TypeUtilities.GetTypeNames(typeof(ControllerBase));
        Assembly ass = Assembly.GetExecutingAssembly();
        for (int i = 0; i < classes.Length; i++)
        {
            Type t = ass.GetType(classes[i]);
            var controller = (ControllerBase)Activator.CreateInstance(t);
            var data = controller.GetPlayerData();
            if (!_author.ContainsKey(data.Author))
            {
                _author[data.Author] = new List<Type>();
            }
            _author[data.Author].Add(t);
            _datas[t] = data;
        }
    }

    private void CreateAuthorList()
    {
        if (_author.Count == 0)
        {
            _authorList.GetChild(0).gameObject.SetActive(false);
            return;
        }

        for (int j = 1; j < _author.Count; j++)
        {
            Instantiate(_authorList.GetChild(0), _authorList);
        }

        int i = 0;
        foreach (var pair in _author)
        {
            _authorList.GetChild(i).gameObject.SetActive(true);
            _authorList.GetChild(i).Find("AuthorName").GetComponent<Text>().text = pair.Key;
            _authorList.GetChild(i).name = pair.Key;
            i++;
        }
    }

    private void CreateTankList(string author)
    {
        var list = _author[author];
        for (int j = 1; j < list.Count; j++)
        {
            Instantiate(_tankList.GetChild(0), _tankList);
        }

        for (int i = 0; i < list.Count; i++)
        {
            _tankList.GetChild(i).gameObject.SetActive(true);
            _tankList.GetChild(i).Find("Name").GetComponent<Text>().text = _datas[list[i]].Name;
            _tankList.GetChild(i).Find("Base").GetComponent<Image>().sprite = ResourceManager.Instance.Load<Sprite>(_datas[list[i]].BaseImage);
            _tankList.GetChild(i).Find("Gun").GetComponent<Image>().sprite = ResourceManager.Instance.Load<Sprite>(_datas[list[i]].GunImage);
            _tankList.GetChild(i).name = list[i].Name;
        }

        for (int i = list.Count; i < _tankList.childCount; i++)
        {
            _tankList.GetChild(i).gameObject.SetActive(false);
        }
    }

    //当选择一个作者
    public void OnClickedAuthor(GameObject go)
    {
        CreateTankList(go.name);
    }

    /// <summary>
    /// 当点击选择一个坦克
    /// </summary>
    /// <param name="go">The go.</param>
    public void OnClickedTank(GameObject go)
    {
        string t;
        if (_teamSeletor.value == 0)
        {
            t = "";
        }
        else
        {
            t = _teamSeletor.options[_teamSeletor.value].text;
        }
        _players.Add(new KeyValuePair<string, GameObject>(go.name, MakeTank(go.name, t)));
        _playerTeams.Add(t);
    }

    private GameObject MakeTank(string className, string team)
    {
        var go = ResourceManager.Instance.Instantiate("prefab/default/Player", _group);
        go.transform.position = new Vector2(UnityEngine.Random.Range(-5f, 5f), UnityEngine.Random.Range(-5f, 5f));
        go.transform.Find("gun").eulerAngles = new Vector3(0, 0, go.transform.position.ToAngle());
        go.GetComponent<Player>().ControllerClassName = className;
        go.GetComponent<Player>().Team = team;
        return go;
    }

    // Update is called once per frame
    private void Update()
    {
    }

    public void Pause()
    {
        Time.timeScale = (Math.Abs(Time.timeScale - 1.0f) < float.Epsilon) ? 0f : 1f;
    }

    public void Replay()
    {
        for (int i = 0; i < _players.Count; i++)
        {
            if (_players[i].Value != null)
            {
                Destroy(_players[i].Value);
            }
            _players[i] = new KeyValuePair<string, GameObject>(_players[i].Key, MakeTank(_players[i].Key, _playerTeams[i]));
        }
    }

    public void Clear()
    {
        for (int i = 0; i < _players.Count; i++)
        {
            if (_players[i].Value != null)
            {
                Destroy(_players[i].Value);
            }
        }
        _playerTeams.Clear();
        _players.Clear();
    }
}